import React, {useEffect, useRef, useState} from 'react';
import {Button, Form, Input, message,} from 'antd';
import {connect} from 'umi';
import '@/pages/book/components/BaseView.less';
import {Editor} from "@tinymce/tinymce-react";
import styles from "@/pages/book/create/components/Step2/index.less";
import {formItemLayout} from "@/pages/book/create/components/Step2";
import {prefix, filePickerCallBack, imgUploadHandler} from "@/pages/book/components/BookView";

const Step3 = ({data, dispatch, submitting }) => {
  const [form] = Form.useForm();
  const FormItem = Form.Item;
  const editorRef = useRef(null);
  const [content, setContent] = useState('');

  useEffect(() => {
    if (data && data.id) {
      form.setFieldsValue({
        id: data.id,
      });
    }
  }, [data]);

  useEffect(() => {
    form.setFieldsValue({pubContent: content});
  }, [content]);

  const {getFieldsValue} = form;

  const onPrev = () => {
    if (dispatch) {
      const values = getFieldsValue();
      dispatch({
        type: 'bookInfo/saveStepFormData',
        payload: {...data, ...values},
      });
      dispatch({
        type: 'bookInfo/saveCurrentStep',
        payload: 'info',
      });
    }
  };

  const doSave = async (values) => {
    if (!values.pubContent) {
      message.error("请描述详情！");
      return;
    }
    if (dispatch) {
      dispatch({
        type: 'bookInfo/submitStepForm',
        payload: values,
      });
    }
  };

  return (
    <>
      <Form
        layout="vertical"
        style={{height: '40px'}}
        form={form}
        className={styles.stepForm}
        hideRequiredMark
        onFinish={doSave}
      >
        <FormItem name="id" noStyle>
          <Input type="hidden"/>
        </FormItem>
        <FormItem name="pubContent" noStyle>
          <textarea hidden
                    value={content} onChange={(e) => setContent(e.target.value)}/>
        </FormItem>
        <FormItem
          wrapperCol={{
            xs: {
              span: 24,
              offset: formItemLayout.labelCol.span,
            },
            sm: {
              span: formItemLayout.wrapperCol.span,
              offset: 10,
            },
          }}
        >
          <Button type="primary" onClick={form.submit} loading={submitting}>
            提交
          </Button>
          <Button onClick={onPrev} style={{ marginLeft: 8, }}>
            上一步
          </Button>
        </FormItem>
      </Form>
        <Editor
          onInit={(evt, editor) => {
            editorRef.current = editor;
          }}
          init={{
            height: '750px',
            width: '100%',
            menubar: true,
            language: 'zh_CN',
            branding: false,
            resize: false,
            object_resizing: 'img',
            images_upload_url: `${prefix}/info/upload`,
            images_upload_credentials: false,
            convert_urls: false,
            file_picker_types: 'media',
            mobile: {
              width: '100%',
              height: 'calc(100% - 40px)',
              menubar: true,
              object_resizing: 'img',
              toolbar: ['formatselect |fullscreen image bold italic bullist numlist | alignleft aligncenter alignright alignjustify link unlink undo redo | fontselect | fontsizeselect outdent indent paste | charmap emoticons',
              ],
            },
            plugins: [
              'advlist autolink lists link image charmap print preview anchor',
              'searchreplace visualblocks code fullscreen',
              'insertdatetime media table paste wordcount ',
              'importcss directionality visualchars template codesample hr pagebreak nonbreaking toc imagetools textpattern noneditable quickbars emoticons'
            ],
            paste_data_images: true,
            toolbar: ['formatselect | bold italic | underline strikethrough | forecolor backcolor | blockquote bullist numlist | alignleft aligncenter alignright alignjustify | link unlink | undo redo | '+
            'fontselect | fontsizeselect | outdent indent | paste removeformat | charmap emoticons | table image | code preview fullscreen',
            ],
            save_onsavecallback: () => {form.submit();},
            video_template_callback: (video) => `<span class="mce-preview-object mce-object-video" contenteditable="false" data-mce-object="video" data-mce-p-allowfullscreen="allowfullscreen" data-mce-p-frameborder="no" data-mce-p-scrolling="no" data-mce-p-src='${video.source}' data-mce-p-width='${video.width}' data-mce-p-height='${video.height}' data-mce-p-controls="controls" data-mce-html="%20"> <video width='${video.width}' height='${video.height}' controls="controls"> <source src='${video.source}' type='${video.sourcemime}'></source> </video> </span>`,
            images_upload_handler: (img, success, failure) => imgUploadHandler(img, success, failure, form),
            file_picker_callback: (callback, value, meta) => filePickerCallBack(callback, value, meta, form),
          }}
          onEditorChange={(e) => setContent(e)}
          value={content}
        />
    </>
  );
};

export default connect(({bookInfo, loading}) => ({
  submitting: loading.effects['bookInfo/submitStepForm'],
  data: bookInfo.step,
  privacyEnum: bookInfo.privacyEnum,
}))(Step3);
